package net.aimeizi.quartz.quartz;

import net.aimeizi.quartz.model.ScheduleJob;
import net.aimeizi.quartz.model.ScheduleJobLog;
import net.aimeizi.quartz.service.ScheduleJobService;
import net.aimeizi.quartz.vo.ScheduleJobVo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class SyncJobFactory extends QuartzJobBean {

    /* 日志对象 */
    private static final Logger LOG = LoggerFactory.getLogger(SyncJobFactory.class);

    @Autowired
    private ScheduleJobService scheduleJobService;

    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        LOG.info("SyncJobFactory execute");
        JobDataMap mergedJobDataMap = context.getMergedJobDataMap();
        ScheduleJob scheduleJob = (ScheduleJob) mergedJobDataMap.get(ScheduleJobVo.JOB_PARAM_KEY);

        String url = scheduleJob.getUrl().trim();

        if (url.indexOf("?") > -1) {
            url = url + "&seq=&job_id=" + scheduleJob.getScheduleJobId() + "&start_time=" + new Date().getTime();
        } else {
            url = url + "?seq=&job_id=" + scheduleJob.getScheduleJobId() + "&start_time=" + new Date().getTime();
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
        System.out.println(dateFormat.format(new Date()) + ":" + url);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response;
        try {
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            System.out.println(dateFormat.format(new Date()) + EntityUtils.toString(entity, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
